class BoardFile < ActiveRecord::Base
	#belongs_to :board_post

	validates_presence_of :file_name ,:mime_type, :length 
#, :register_date
	validates_numericality_of :length
	#validates_associated :board_post_id

	attr_writer :data

	#include ErrorRaising

	def file=(file)
		self.file_name = file.original_filename
		self.length = file.length
		self.mime_type = file.content_type
		self.data = file.read
	end

	def after_save
		self.mkdirs
		File.open(self.file_path,'w') do |f|
			f.write(@data)
		end

	end

	def before_destroy
		if(File.exists?(self.file_path))
			File.delete self.file_path
		end
	end

	def get_file_content
		File.read self.file_path
	end

	def mkdirs
		_dir = ''
		self.dir_path.each("/") do |dir|
			_dir = _dir + dir
			if(File.exists?(_dir))
			else
			 	Dir.mkdir(_dir)
			end
		end
	end

	def dir_path
		reg_year_month = self.register_date.strftime("%Y%m")
		reg_date = self.register_date.strftime("%d")
		RAILS_ROOT+"/attachments/board_files/#{reg_year_month}/#{reg_date}"
	end

	def file_path
		#self.dir_path+"/#{self.register_date}/#{self.id}"
		self.dir_path+"/#{self.id}"
	end

end
